<?php
/**
 * Created by PhpStorm.
 * User: peter
 * Date: 2018/6/17
 * Time: 下午7:54
 */

namespace app\activity\logic;


use app\model\MemberLoginToken;
use extend\Functions;
use extend\STATUS_CODE;
use think\facade\Cache;

class Member
{
    /**
     * @purpose 通过token获取用户信息
     * @param string $token
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function infoByToken(
        string $token,
        string $client_type): array
    {
        $login  = new MemberLoginToken();
        $result = $login
            ->alias('l')
            ->where('l.'.$client_type.'_token', $token)
            ->join('member m', 'l.uid=m.uid')
            ->field('l.uid,m.uuid,m.mobile,m.password,m.nickname,m.sex,m.balance,m.username,m.avatar,m.frozen,m.is_develop')
            ->find();
        return Functions::result(
            STATUS_CODE::SUCCESS,
            $result
        );
    }

    /**
     * @purpose 设置昵称
     * @param string $nickname
     * @param int $uid
     * @return array
     */
    public static function setNickname(string $nickname = '', int $uid): array
    {
        if (!$nickname) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '参数错误!'
            );
        }
        $model  = new \app\model\Member();
        $result = $model
            ->isUpdate(true)
            ->save(
                ['nickname' => $nickname],
                ['uid' => $uid]
            );
        if ($result) {
            return Functions::result();
        }
        return Functions::result(
            STATUS_CODE::UPDATE_FAIL,
            '设置失败'
        );
    }

    /**
     * @purpose 设置用户名
     * @param string $username
     * @param int $uid
     * @return array
     */
    public static function setUsername(string $username = '', int $uid): array
    {
        if (!$username) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '参数错误'
            );
        }
        $username = strtolower(trim($username));
        if (!preg_match('/^(?!\d+$)[\da-zA-Z]{6,12}$/', $username)) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '用户名格式错误，由6位以上，字母或数字组合'
            );
        }
        $model = new \app\model\Member();
        // 检测是否设置过用户名
        if ($model->where('uid', $uid)->value('username')) {
            return Functions::result(
                STATUS_CODE::FAIL,
                '用户名只可设置一次...!'
            );
        }
        // 检测用户名是否已存在
        if ($model->total(['username' => $username]) > 0) {
            return Functions::result(
                STATUS_CODE::FAIL,
                '用户名已存在'
            );
        }


        $result = $model
            ->isUpdate(true)
            ->save(
                ['username' => $username],
                ['uid' => $uid]
            );
        if ($result) {
            return Functions::result();
        }
        return Functions::result(
            STATUS_CODE::UPDATE_FAIL,
            '设置失败'
        );
    }

    /**
     * @purpose 设置密码
     * @param string $password
     * @param int $uid
     * @return array
     */
    public static function setPassword(string $password = '', int $uid): array
    {
        if (!$password) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '参数错误'
            );
        }
        $model    = new \app\model\Member();
        $password = strtolower(trim($password));
        if (!preg_match('/^[a-zA-Z0-9\.\-\_]{6,}$/', $password)) {
            return Functions::password(
                STATUS_CODE::PARAMETER_ERROR,
                '密码应该在6位数以上，并且由字母与数字组合而成,不区分大小写'
            );
        }
        $password = Functions::password($password);
        $result   = $model
            ->isUpdate(true)
            ->save($password, ['uid' => $uid]);
        if ($result) {
            return Functions::result();
        }
        return Functions::result(
            STATUS_CODE::UPDATE_FAIL,
            '设置失败'
        );
    }

    /**
     * @purpose 编辑密码
     * @param string $old_password
     * @param string $new_password
     * @param int $uid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function editPassword (string $old_password = '', string $new_password, int $uid): array
    {
        if (!$old_password) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '请输入旧密码'
            );
        }
        if (!$new_password) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '请输入新密码'
            );
        }
        $model      = new \app\model\Member();
        $info = $model
            ->where('uid', $uid)
            ->field('uid,password,encrypt')
            ->find();
        if ($info->password !== Functions::password(strtolower(trim($old_password)), $info->encrypt)) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '旧密码错误'
            );
        }
        if (!preg_match('/^[a-zA-Z0-9\.\-\_]{6,}$/', strtolower(trim($new_password)))) {
            return Functions::password(
                STATUS_CODE::PARAMETER_ERROR,
                '新密码应该在6位数以上，并且由字母与数字组合而成,不区分大小写'
            );
        }
        $password = Functions::password(strtolower(trim($new_password)));
        $result     = $model
            ->isUpdate(true)
            ->save($password, ['uid' => $uid]);

        if ($result) {
            return Functions::result();
        }
        return Functions::result(
            STATUS_CODE::UPDATE_FAIL,
            '修改成功'
        );
    }

    /**
     * @purpose 绑定手机号码
     * @param string $mobile
     * @param string $code
     * @param int $uid
     * @return array
     */
    public static function bindMobile (
        string $mobile = '',
        string $code = '',
        int $uid): array
    {
        if (!$mobile) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '缺少手机号码'
            );
        }
        if (!$code) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '缺少验证码'
            );
        }
        $model          = new \app\model\Member();
        if ($model->total(['mobile' => $mobile]) > 0) {
            return Functions::result(
                STATUS_CODE::FAIL,
                '该号码已被其他账号绑定'
            );
        }
        $self_code = Cache::store('redis')->get($mobile);
        if (!$self_code) {
            return Functions::result(
                STATUS_CODE::FAIL,
                '验证码已过期'
            );
        }
        if ((string) $self_code !== (string) $code) {
            return Functions::result(
                STATUS_CODE::FAIL,
                '验证码错误'
            );
        }
        // 验证码验证成功,清除缓存
        Cache::store('redis')->rm($mobile);
        $result         = $model
            ->isUpdate(true)
            ->save(['mobile' => $mobile], ['uid' => $uid]);
        if ($result) {
            return Functions::result();
        }
        return Functions::result(
            STATUS_CODE::FAIL,
            '手机号码绑定失败!'
        );
    }

    /**
     * @purpose 更换手机号码
     * @param string $old_mobile
     * @param string $old_code
     * @param string $new_mobile
     * @param string $new_code
     * @param int $uid
     * @return array
     */
    public static function changeMobile (
        string $old_mobile = '',
        string $old_code = '',
        string $new_mobile = '',
        string $new_code = '',
        int $uid
    ) :array
    {
        $self_old_code = Cache::store('redis')->get($old_mobile);
        $self_new_code = Cache::store('redis')->get($new_mobile);
        if (!$self_old_code) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '旧号码验证码已过期!'
            );
        }
        if (!$self_new_code) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '新号码验证码已过期!'
            );
        }
        if ((string) $self_old_code !== (string) $old_code) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '旧号码验证码错误'
            );
        }
        if ((string) $self_new_code !== (string) $new_code) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '新号码验证码错误'
            );
        }
        $model          = new \app\model\Member();
        if ($model->total(['mobile' => $new_mobile]) > 0) {
            return Functions::result(
                STATUS_CODE::FAIL,
                '该号码已被其他账号绑定'
            );
        }
        // 验证码验证成功,清除缓存
        Cache::store('redis')->rm($old_mobile);
        Cache::store('redis')->rm($new_mobile);
        $result         = $model
            ->isUpdate(true)
            ->save(['mobile' => $new_mobile], ['uid' => $uid]);
        if ($result) {
            return Functions::result();
        }
        return Functions::result(
            STATUS_CODE::FAIL,
            '手机号码绑定失败!'
        );
    }
}